package com.java.hohenheim.springplatform.web.jwt;

import com.java.hohenheim.springplatform.define.ResultCodes;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author Hohenheim
 * @date 2020/9/1
 * @description
 */
@Component
@Slf4j
public class UserTokenUtils extends JwtUtils {
    @Autowired
    private TokenConfig mUserTokenConfig;

    private final String KEY_USER_ID = "userId";

    public String createUserToken(long userId) {
        HashMap<String, Object> claimMap = new HashMap<>();
        claimMap.put(KEY_USER_ID, userId);
        return createToken(claimMap, mUserTokenConfig);
    }

    /**
     * 获取用户ID
     * @return token中包含的用户名
     */
    public long getUserId(String token) {
        Claims claims = getClaimsFromToken(token, mUserTokenConfig.getSignKey(),true);
        Object userIdObj = claims.get(KEY_USER_ID);

        return null == userIdObj ? 0 : (Long) userIdObj;
    }

    /**
     * 校验token是否正确
     *
     * @param token 凭证
     * @return 检测结果，如果检测成功，还包含UserToken信息对象
     */
    public TokenCheckResult<UserToken> verify(String token) {
        TokenCheckResult<JwtToken> result = super.verify(token, mUserTokenConfig.getSignKey());
        TokenCheckResult<UserToken> userTokenCheckResult = new TokenCheckResult<>();
        BeanUtils.copyProperties(result, userTokenCheckResult, "jwtToken");

        if(result.getResult()==ResultCodes.RETURN_SUCCESS && null!=result.getJwtToken()) {
            UserToken userToken = new UserToken();
            BeanUtils.copyProperties(result.getJwtToken(), userToken);
            userTokenCheckResult.setJwtToken(userToken);
            userToken.setUserId(getUserId(token));
        }

        return userTokenCheckResult;
    }
}